<?php
class RM_Insurances extends RM_Model_Multilingual
{
    protected $_name = 'rm_insurances';
    protected $_rowClass = 'RM_Insurances_Row';

    /**
     * Returns all rows that are assigned to unit directly + all global insurances
     *
     * @param RM_Unit_Row $unit
     * @return Zend_Db_Table_Rowset_Abstract
     */
    function getByUnit(RM_Unit_Row $unit, $compulsoryOnly = false)
    {
        $nonGlobalSelect = $this->select()->setIntegrityCheck(false)
            ->from(array('c' => 'rm_insurances'))
            ->where('enabled=1')
            ->joinInner(array('uc' => 'rm_unit_insurances'), 'uc.insurance_id = c.id AND uc.unit_id = '.$unit->id, array());

        $globalSelect = $this->select()
            ->from(array('d' => 'rm_insurances'))
            ->where('global=1')
            ->where('enabled=1');

        if ($compulsoryOnly) {
            $nonGlobalSelect->where('compulsory=1');
            $globalSelect->where('compulsory=1');
        }

        return $this->fetchAll($this->select()->union(array(
            $nonGlobalSelect,
            $globalSelect
        )));
    }
}